﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GA_Scheduler
{
    public class RoomSizePenalty : IPenalty
    {
        int cScore;
        object lockObj = new object();

        /// <summary>
        /// Nominal score
        /// </summary>
        public int Score
        {
            get;
            set;
        }

        /// <summary>
        /// Score which calculated during executing. 
        /// </summary>
        public int CalculatedScore
        {
            get { return cScore; }
        }

        Schedule _sch;

        /// <summary>
        /// Check rooms overlaping.
        /// </summary>
        /// <param name="sch">Schedule for checking</param>
        /// <returns></returns>
        public bool Execute(Schedule sch)
        {
            _sch = sch;
            if (Environment.ProcessorCount > 1)
            {
                ParallelExecute();
            }
            else
            {
                NonParallelExecute();
            }

            if (cScore > 0)
                return true;
            else
                return false;
        }

        private void ParallelExecute()
        {
            Parallel.ForEach(_sch.Genes, gen =>
            {
                if(gen.Class.NumberOfSeats() > gen.Room.Size)
                {
                    lock (lockObj)
                    {
                        cScore += Score;
                    }
                }
            }
           );
        }

        private void NonParallelExecute()
        {
            foreach (var gen in _sch.Genes)
            {
                if (gen.Class.NumberOfSeats() > gen.Room.Size)
                {
                    lock (lockObj)
                    {
                        cScore += Score;
                    }
                }
            }
        }

        public string Name
        {
            get { return "RoomPenalty"; }
            set
            {
                throw new NotImplementedException();
            }
        }
    }
}
